var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var emailsRouter = require('./routes/emails')
var articleRouter = require('./routes/article')
var checkRouter = require('./routes/check')
var knowledgeRouter = require('./routes/knowledge')
var djknowRouter = require('./routes/djknow')
var refersRouter = require('./routes/refers')
var branchsRouter = require('./routes/branchs')
var app = express();
//配置body-parser
// 只要加上这个配置，则在req请求对象上会多出来一个属性：body
// 因此可以直接通过req.body来获取表单post请求体数据
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
//配置跨域以及请求头
app.use((req, res, next) => {
  //设置请求头
  res.set({
    'Access-Control-Allow-Credentials': true,
    'Access-Control-Max-Age': 1728000,
    'Access-Control-Allow-Origin': req.headers.origin || '*',
    'Access-Control-Allow-Headers': 'X-Requested-With,Content-Type',
    'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS',
    'Content-Type': 'application/json; charset=utf-8'
  })
  req.method === 'OPTIONS' ? res.status(204).end() : next()
})

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/emails', emailsRouter);
app.use('/article', articleRouter)
app.use('/check', checkRouter)
app.use('/knowledge', knowledgeRouter)
app.use('/djknow', djknowRouter)
app.use('/refers', refersRouter)
app.use('/branchs', branchsRouter)

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
